<?php
namespace Demomodule\ShopRepository;
class TreeRepository{
    //表名称
    private $tableName;
    //父级字段名称
    private $parentField;
    //主键字段名称
    private $primaryKey;
    //物化路径字段名称
    private $materializedPathField;
    //菜单级别名称
    private $levelField;

    /**
     * 构造函数
     */
    public function __construct($tableName,$parentField,$primaryKey,$materializedPathField,$levelField){
        $this->tableName=$tableName;
        $this->parentField=$parentField;
        $this->primaryKey=$primaryKey;
        $this->materializedPathField=$materializedPathField;
        $this->levelField=$levelField;
    }
    /**
     * 以树形结构获取所有菜单项
     */
    public function getTree(){
        $data=$this->tableName->select();
        $tree=[];
        foreach($data as $item){
            $tree[$item[$this->primaryKey]]=$item;
        }
        foreach($tree as $item){
            $parentId=$item[$this->parentField];
            if($parentId){
                $tree[$parentId][$this->childField][$item[$this->primaryKey]]=$item;
            }
        }
        return $tree;
    }
    /**
     * 以树形结构获取指定菜单的所有子菜单项
     */
    public function getChildren($parentId){
        $tree=$this->getTree();
        if(isset($tree[$parentId])){
            return $tree[$parentId][$this->childField];
        }
        return [];
    }
    /**
     * 新增菜单项
     */
    public function add($item){
        $item[$this->materializedPathField]=$item[$this->parentField];
        $item[$this->levelField]=1;
        return $this->tableName->insert($item);
    }
    /**
     * 修改菜单项
     */
    public function update($item){
        $item[$this->materializedPathField]=$item[$this->parentField];
        $item[$this->levelField]=1;
        return $this->tableName->update($item);
    }
    /**
     * 删除菜单项
     */
    public function delete($id){
        return $this->tableName->delete($id);
    }


    
}